import {
  Button,
  Card,
  Divider,
  Space,
  Table,
  Modal,
  Input,
  Upload,
  message,
  Form,
} from "antd";
import { useEffect, useState } from "react";
import "./index.css";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import {
  reqTrademark,
  reqRemove,
  reqAddTrademark,
  reqTrademarkDetail,
  reqUpdateTrademark,
} from "@/api/product/trademark/trademark";
import type { logDetail } from "@/api/product/trademark/model/trademarkTypes";
// import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
/* import type { FormInstance } from 'antd/es/form';
import React from "react"; */
export default function TradeMark() {
  const [loading, setLoading] = useState(false);
  let [imageUrl, setImageUrl] = useState<string>("");
  //品牌名字
  const [brand, setBrand] = useState<string>("");
  //品牌id
  const [tradeId, setTradeId] = useState<number | undefined>();

  const onChange: UploadProps["onChange"] = ({ file }) => {
    if (file.response) {
      setImageUrl(file.response.data);
      
    }
  };

  //验证图片上传格式
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    // console.log(file);

    return isJpgOrPng && isLt2M;
  };

  // 声明当前页码
  const [current, setCurrent] = useState<number>(1);
  //声明总数
  const [total, setTotal] = useState<number>(0);
  //声明每页展示数量
  const [pageSize, setPageSize] = useState<number>(5);

  //数据源
  const [trademark, setTrademark] = useState<logDetail[]>([]);

  //弹窗状态
  const [isShow, setIsShow] = useState<any>(false);
  //添加弹窗展示
  const changeIsShow = () => {
    setIsShow(true);
  };
  //取消按钮
  const cancle = () => {
    setImageUrl("");
    if (imageUrl) {
      setImageUrl("");
    }
    setBrand("");
    setTradeId(undefined);
    console.log('1111111');
    
    setIsShow(false);
  };
  //确定按钮
  const confirm = async () => {
    // console.log(12);
    console.log(imageUrl, "......");
    if (tradeId) {
      let params = {
        logoUrl: imageUrl,
        tmName: brand,
        id: tradeId,
      };

      const res = await reqUpdateTrademark(params);
      message.success("修改数据成功");
    } else {
      
      
      if (imageUrl.length > 0 && brand.length > 0) {
        console.log(imageUrl);
        const params = {
          logoUrl: imageUrl,
          tmName: brand,
        };
        const res = await reqAddTrademark(params);
        console.log(res);

        message.success("添加数据成功");
      }
    }

    setImageUrl("");
    if (imageUrl) {
      setImageUrl("");
    }
    setBrand("");
    setTradeId(undefined);

    getTrademark();

    setIsShow(false);
  };

  //删除品牌
  const deleteTrade = (id: number) => {
    return async () => {
      await reqRemove(id);
      getTrademark();
      // setCurrent(1)
      message.success("删除成功");
    };
  };

  //获取指定品牌信息
  const getOneTrademark = (id: number) => {
    return async () => {
      const res = await reqTrademarkDetail(id);
      setBrand(res.tmName);
      setImageUrl(res.logoUrl);
      // console.log(imageUrl)

      setTradeId(res.id);
      setIsShow(true);
    };
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const columns: ColumnsType<any> = [
    {
      title: "序号",
      align: "center",
      width: "80",
      render: (key: any, row: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      width: "80",
      dataIndex: "tmName",
      align: "center",
    },
    {
      title: "品牌log",
      dataIndex: "logoUrl",
      width: "120",
      render(row: string) {
        return (
          <>
            <img src={row} alt="" className="logImg" />
          </>
        );
      },
    },
    {
      title: "操作",
      align: "center",
      fixed: "right",
      width: "300",
      render: (row: logDetail) => {
        //  当配置项存在  dataIndex 时，render 第一个参数为 对应的 dataIndex的值，第二个参数为这一行数据的对象，第三个参数为 下标
        //  当配置项不存在  dataIndex 时，render 第一个参数为 这一行数据对象

        return (
          <>
            <Button
              onClick={getOneTrademark(row.id)}
              icon={<EditOutlined />}
              type="primary"
            >
              编辑
            </Button>
            <Button
              onClick={deleteTrade(row.id)}
              className="ml"
              icon={<DeleteOutlined />}
              danger
              type="primary"
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

  //获取品牌列表信息
  const getTrademark = async (page = current, limit = pageSize) => {
    const res = await reqTrademark(page, limit);
    console.log(res);

    setTrademark(res.records);
    setTotal(res.total);
  };

  //获取最新的品牌名字
  const changeBranch = (e: any) => {
    setBrand(e.target.value);
  };

  useEffect(() => {
    getTrademark();
  }, [current, pageSize]);
  useEffect(() => {
    // console.log(imageUrl);
  }, [imageUrl]);

  return (
    <>
      <div className="pack">
        <Card title="" className="card">
          <Button type="primary" icon={<PlusOutlined />} onClick={changeIsShow}>
            添加
          </Button>
          <Modal
            title="添加品牌信息"
            visible={isShow}
            onOk={confirm}
            onCancel={cancle}
          >
            <Form
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 14 }}
              layout="horizontal"
              style={{ maxWidth: 600 }}
            >
              <Form.Item label="品牌用户名" rules={[{ required: true ,validateTrigger:'onblur'}]}> 
                <Input value={brand} onChange={changeBranch} />
              </Form.Item>

              <Form.Item label="品牌log" rules={[{ required: true }]}>
                <Upload
                  action="/api/admin/product/upload"
                  listType="picture-card"
                  beforeUpload={beforeUpload}
                  onChange={onChange}
                  maxCount={1}
                  showUploadList={false}
                >
                  {imageUrl ? (
                    <img
                      src={imageUrl}
                      alt="avatar"
                      style={{ width: "100%" }}
                    />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </Form.Item>
            </Form>
          </Modal>
          <Divider />
          <Table
            bordered
            scroll={{ x: 1200 }}
            columns={columns}
            dataSource={trademark}
            rowKey="id"
            pagination={{
              total,
              current,
              pageSize,
              pageSizeOptions: [5, 10, 15, 20],
              showQuickJumper: true, //快速跳转至某页
              showSizeChanger: true,
              showTotal: (total: number) => {
                return <span>总数：{total}条</span>;
              },
              onChange: (page: number, pageSize: number) => {
                //更新页码及每页展示数量状态
                // console.log(page);
                setCurrent(page);
                setPageSize(pageSize);
              },
            }}
          />
        </Card>
      </div>
    </>
  );
}
